import dotenv from 'dotenv';
import { jest } from '@jest/globals';

// 加载测试环境变量
dotenv.config({ path: '.env.test' });

// 设置测试环境变量
process.env.NODE_ENV = 'test';
process.env.DB_HOST = process.env.TEST_DB_HOST || 'localhost';
process.env.DB_PORT = process.env.TEST_DB_PORT || '3306';
process.env.DB_NAME = process.env.TEST_DB_NAME || 'xuantuotuo_test';
process.env.DB_USER = process.env.TEST_DB_USER || 'test';
process.env.DB_PASS = process.env.TEST_DB_PASS || 'test';
process.env.REDIS_HOST = process.env.TEST_REDIS_HOST || 'localhost';
process.env.REDIS_PORT = process.env.TEST_REDIS_PORT || '6379';

// 全局测试配置
global.testTimeout = 30000;

// 测试数据库连接配置
export const testDbConfig = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  multipleStatements: true,
  timezone: 'Z'
};

// 模拟日志器（减少测试输出噪音）
export const mockLogger = {
  info: jest.fn(),
  error: jest.fn(),
  warn: jest.fn(),
  debug: jest.fn()
};

// 测试工具函数
export const testUtils = {
  // 等待异步操作完成
  waitFor: (ms = 100) => new Promise(resolve => setTimeout(resolve, ms)),
  
  // 创建模拟玩家数据
  createMockPlayer: (overrides = {}) => ({
    id: 'test-player-1',
    name: 'TestPlayer',
    seatIndex: 0,
    isReady: false,
    status: 'online',
    cards: [],
    ...overrides
  }),
  
  // 创建模拟房间数据
  createMockRoom: (overrides = {}) => ({
    id: 'TEST01',
    name: 'Test Room',
    hostId: 'test-player-1',
    status: 'waiting',
    playerCount: 1,
    maxPlayers: 3,
    players: [],
    createdAt: new Date(),
    ...overrides
  }),
  
  // 生成测试用的扑克牌
  createTestCards: (count = 8) => {
    const cards = [];
    const suits = ['hearts', 'spades', 'diamonds', 'clubs'];
    const ranks = ['7', '8', '9', '10', 'J', 'Q', 'K', 'joker'];
    
    for (let i = 0; i < count; i++) {
      const suit = suits[i % suits.length];
      const rank = ranks[i % ranks.length];
      const displayName = rank === 'joker'
        ? (i % 2 === 0 ? '大王' : '小王')
        : `${suit === 'hearts' || suit === 'diamonds' ? '红' : '黑'}${rank}`;

      const card = {
        id: `${suit}-${rank}-${i}`,
        suit,
        rank,
        power: 10 + i,
        displayName,
        type: 'test'
      };

      card.toJSON = () => ({
        id: card.id,
        suit: card.suit,
        rank: card.rank,
        power: card.power,
        displayName: card.displayName,
        type: card.type
      });

      cards.push(card);
    }
    
    return cards;
  },
  
  // 清理数据库测试数据
  cleanupTestData: async (db) => {
    if (!db) return;
    
    try {
      await db.execute('DELETE FROM game_actions WHERE session_id LIKE "test-%"');
      await db.execute('DELETE FROM game_sessions WHERE id LIKE "test-%"');
      await db.execute('DELETE FROM room_players WHERE room_id LIKE "TEST%"');
      await db.execute('DELETE FROM game_rooms WHERE id LIKE "TEST%"');
    } catch (error) {
      console.error('清理测试数据失败:', error);
    }
  }
};

// Jest全局配置
beforeAll(() => {
  // 禁用真实日志输出
  jest.spyOn(console, 'log').mockImplementation(() => {});
  jest.spyOn(console, 'info').mockImplementation(() => {});
  jest.spyOn(console, 'warn').mockImplementation(() => {});
  jest.spyOn(console, 'error').mockImplementation(() => {});
});

afterAll(() => {
  // 恢复控制台输出
  console.log.mockRestore?.();
  console.info.mockRestore?.();
  console.warn.mockRestore?.();
  console.error.mockRestore?.();
});
